export default function (data) {
    loadCSS()
    return buildTable(data)
}

function loadCSS() {
    var cssId = 'bootstrapCSS';  // you could encode the css path itself to generate id..
    if (!document.getElementById(cssId)) {
        var head = document.getElementsByTagName('head')[0];
        var link = document.createElement('link');
        link.id = cssId;
        link.rel = 'stylesheet';
        link.type = 'text/css';
        link.href = '/Direct/com.nebutown.workflow.root.Root/commonui/commoncss/bootstrap.css';
        link.media = 'all';
        head.appendChild(link);
    }
}

function buildTable(data) {
    let result = '<table class="table table-bordered" id="${data.id}">'
    result += '<style>.center {margin: 0.5em;}</style>'
    result += buildHeader(data.defs)
    console.log("rows:" + JSON.stringify(data.rows))
    data.rows['data'].forEach(d => {
        result += buildTR(data.defs, d);
    })
    return result + '</table>'
}

function buildHeader(def) {
    let result = "<tr>"
    def.forEach(column => {
        result += buildTH(column.header)
    })
    return result + "</tr>"

}

function buildTR(def, data) {
    let result = "<tr>"
    def.forEach(column => {
        result += buildTD(data[column.column])
    })
    return result + "</tr>"
}

function buildTD(content) {
    return '<td class="table-bordered center">' + content + '</td>'
}

function buildTH(content) {
    return '<th class="table-bordered center">' + content + '</th>'
}
